package main

import (
	//docs 目录为swagger自动生成，不建议手动修改
	_ "MoSkeleton/bootstrap/main/docs"
	"MoSkeleton/bootstrap/web"
	"MoSkeleton/framework/application"
	"MoSkeleton/global/actuator"
	"context"
	"fmt"
	"os"
	"os/signal"
	"syscall"
	"time"
)

// @title MoSkeleton Swagger API接口文档
// @version 1.0
// @description MoSkeleton, 本系统可适用于所有的Web应用程序，如网站管理后台，网站会员中心，CMS，CRM，OA等
// @name MoSkeleton
// @securityDefinitions.apikey  ApiKeyAuth
// @in                          header
// @name                        Authorization
// @BasePath /

var app application.Application

func main() {
	fmt.Print("start app: MoSke\n")
	actuator.MakeStarting()
	app = new(web.WebApplication)
	notifyChain := make(chan int)
	go app.Run(notifyChain)
	waitForShutdown(notifyChain)
}

func waitForShutdown(notifyChain <-chan int) {
	sigs := listenSignal()
	for {
		select {
		case n := <-notifyChain:
			switch n {
			case 1:
				actuator.MakeStartUp()
			case -1:
				actuator.MakeShutDown()
				return
			}
		case <-sigs:
			fmt.Print("receive shutdown: MoSke\n")
			actuator.MakeShutDown()
			ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
			defer cancel() // 确保释放资源
			app.Shutdown(ctx)
			//time.Sleep(1 * time.Minute)
			return
		}
	}
}
func listenSignal() <-chan os.Signal {
	// 监听终止信号
	sigs := make(chan os.Signal, 1)
	signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
	return sigs
}
